<?php

/**
 * 主题管理
 */
namespace app\topics\model;

use app\system\model\SystemModel;

class TopicsDetailReplyModel extends SystemModel {

    protected $infoModel = [
        'pri' => 'reply_id',
        'validate' => [
            'detail_id' => [
                'empty' => ['', '主题ID不存在!', 'must', 'all'],
            ],
            'user_id' => [
                'empty' => ['', '用户ID不正确!', 'must', 'all'],
            ],
            'markdown' => [
                'empty' => ['', '请输入回复内容！', 'must', 'all'],
            ],
        ],
        'format' => [
            'detail_id' => [
                'function' => ['intval', 'all'],
            ],
            'user_id' => [
                'function' => ['intval', 'all'],
            ],
            'floor' => [
                'function' => ['intval', 'all'],
            ],
            'html' => [
                'callback' => ['parseHtml', 'all']
            ]

        ],
        'into' => 'detail_id,user_id,create_time,floor,markdown,ip',
        'out' => '',
    ];

    public function parseHtml($field, $filedData) {
        $data = $this->getData();
        return target('topics/TopicsDetail')->changeHtml($data['markdown']);
    }



    protected function base($where) {
        return $this->table('topics_detail_reply(A)')
            ->join('topics_user(B)', ['B.user_id', 'A.user_id'])
            ->join('topics_detail(C)', ['C.detail_id', 'A.detail_id'])
            ->field(['A.*', 'B.username(show_name)', 'B.avatar', 'C.title', 'C.type'])
            ->where((array)$where);
    }

    public function loadList($where = array(), $limit = 0, $order = '') {
        $list = $this->base($where)
            ->limit($limit)
            ->order($order)
            ->select();
        $typeList = target('topics/Topics', 'service')->getTypeAll();
        foreach ($list as $key => $vo) {
            $list[$key]['avatar'] = $vo['avatar'] ? $vo['avatar'] : ROOT_URL . '/public/topics/images/logo.png';
            $list[$key]['url'] = url($typeList[$vo['type']]['info_url'], ['id' => $vo['detail_id']]);
        }
        return $list;
    }

    public function countList($where = array()) {
        return $this->base($where)->count();
    }

    public function getWhereInfo($where) {
        $info = $this->base($where)->find();
        return $info;
    }

    public function saveData($type = 'add', $data = []) {
        $time = time();
        $this->beginTransaction();

        $userInfo = target('topics/TopicsUser')->getInfo($data['user_id']);
        if (!$userInfo['status']) {
            $this->error = '您已被禁用，无法进行发布！';
            return false;
        }
        if (empty($userInfo['avatar'])) {
            $this->error = '设置头像后才可进行内容发布！';
            return false;
        }

        $detailInfo = target('topics/TopicsDetail')->getInfo(intval($data['detail_id']));
        if (empty($detailInfo)) {
            $this->error = '主题不存在！';
            return false;
        }

        $lastInfo = $this->where(['user_id' => $data['user_id']])->order('reply_id desc')->find();
        if ($lastInfo['create_time'] + 30 > time()) {
            $this->error = '30秒内不能再次回复内容！';
            return false;
        }

        $num = $detailInfo['reply_num'] + 1;
        $status = target('topics/TopicsDetail')->edit([
            'detail_id' => $detailInfo['detail_id'],
            'update_time' => $time,
            'reply_num' => $num,
        ]);

        $data['ip'] = \dux\lib\Client::getUserIp();

        if (!$status) {
            $this->rollBack();
            $this->error = target('topics/TopicsNode')->getError();
            return false;
        }

        if ($type == 'add') {
            $data['create_time'] = $time;
            $data['floor'] = $num;
            $id = parent::saveData('add', $data);
            if (!$id) {
                $this->rollBack();
                $this->error = $this->getError();
                return false;
            }
        }
        if ($type == 'edit') {
            $status = parent::saveData('edit', $data);
            if (!$status) {
                $this->rollBack();
                $this->error = $this->getError();
                return false;
            }
        }


        $nodeInfo = target('topics/TopicsNode')->getInfo($detailInfo['node_id']);
        $status = target('topics/TopicsNode')->edit([
            'node_id' => $nodeInfo['node_id'],
            'count_reply' => $nodeInfo['count_reply'] + 1,
            'last_reply_time' => $time,
        ]);
        if (!$status) {
            $this->rollBack();
            $this->error = target('topics/TopicsNode')->getError();
            return false;
        }

        if($nodeInfo['point_reply_num']) {
            $status = target('member/Points', 'service')->account([
                'user_id' => $data['user_id'],
                'points' => $nodeInfo['point_reply_num'],
                'type' => $nodeInfo['point_reply_type'],
                'deduct' => true,
                'remark' => '回帖' . $nodeInfo['point_reply_type'] ? '增加' : '扣除' . '积分'
            ]);
            if (!$status) {
                $this->error = target('member/Points', 'service')->getError();
                return false;
            }
        }
        $this->commit();
        return true;
    }


}